<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <div class="text item">
        <el-form
          :model="questionsForm"
          :rules="questionsRules"
          ref="questionsForm"
          label-width="120px"
        >
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              style="width: 400px"
              v-model="questionsForm.subjectID"
              placeholder="请选择"
              @change="changeSubject"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              style="width: 400px"
              v-model="questionsForm.catalogID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in directorysList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              style="width: 400px"
              v-model="questionsForm.enterpriseID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in companysList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" prop="city">
            <el-select
              style="width: 200px"
              v-model="questionsForm.province"
              placeholder="请选择"
              @change="changeCity"
            >
              <el-option
                v-for="(item, index) in provinceList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              style="width: 200px"
              v-model="questionsForm.city"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in cityList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向：" prop="direction">
            <el-select
              style="width: 400px"
              v-model="questionsForm.direction"
              placeholder="请选择"
            >
              <el-option label="o2o" value="o2o"></el-option>
              <el-option label="外包服务" value="外包服务"></el-option>
              <el-option label="企业服务" value="企业服务"></el-option>
              <el-option label="互联网金融" value="互联网金融"></el-option>
              <el-option label="企业咨询" value="企业咨询"></el-option>
              <el-option label="互联网" value="互联网"></el-option>
              <el-option label="电子商务" value="电子商务"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group
              @change="changeType"
              v-model="questionsForm.questionType"
            >
              <el-radio :label="'1'">单选</el-radio>
              <el-radio :label="'2'">多选</el-radio>
              <el-radio :label="'3'">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="questionsForm.difficulty">
              <el-radio :label="'1'">简单</el-radio>
              <el-radio :label="'2'">一般</el-radio>
              <el-radio :label="'3'">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干：" prop="question">
            <quill-editor
              @blur="$refs.questionsForm.validateField('question')"
              v-model="questionsForm.question"
            >
            </quill-editor>
          </el-form-item>

          <el-form-item
            v-if="questionsForm.questionType === '1'"
            label="选项："
          >
            <div
              class="radio-options"
              v-for="(item, index) in questionsForm.options"
              :key="item.code"
            >
              <el-radio
                style="margin-right: 0"
                v-model="radioData"
                :label="item.code"
                >{{ item.code }}：</el-radio
              >
              <el-input v-model="item.title" class="radio-input"></el-input>
              <div class="father-a">
                <el-upload
                  v-if="!item.img"
                  class="uploader-img"
                  action="http://192.168.69.128:3030/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  @click.native="changeUpload(item.code)"
                >
                  上传图片
                </el-upload>
                <img
                  v-else
                  :src="item.img"
                  style="vertical-align: middle"
                  class="uploader-img"
                />
                <a class="upload-close" @click="closeUploadImg(index)">×</a>
              </div>
            </div>

            <el-button
              :disabled="questionsForm.questionType === '1'"
              type="danger"
              size="small"
              >+增加选项与答案</el-button
            >
          </el-form-item>

          <el-form-item
            v-if="questionsForm.questionType === '2'"
            label="选项："
          >
            <div
              class="radio-options"
              v-for="(item, index) in questionsForm.options"
              :key="index"
            >
              <el-checkbox v-model="item.isRight"
                >{{ item.code }}：</el-checkbox
              >
              <el-input v-model="item.title" class="radio-input"></el-input>

              <div class="father-a">
                <el-upload
                  v-if="!item.img"
                  class="uploader-img"
                  action="http://192.168.69.128:3030/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  @click.native="changeUpload(item.code)"
                >
                  上传图片
                </el-upload>
                <img
                  v-else
                  style="vertical-align: middle"
                  :src="item.img"
                  class="uploader-img"
                />
                <a class="upload-close" @click="closeUploadImg(index)">×</a>
              </div>
            </div>
            <el-button
              :disabled="questionsForm.questionType === '1'"
              type="danger"
              size="small"
              @click="addOptions"
              >+增加选项与答案</el-button
            >
          </el-form-item>

          <el-form-item label="解析视频：" prop="videoURL">
            <el-input
              style="width: 400px"
              v-model="questionsForm.videoURL"
            ></el-input>
          </el-form-item>
          <el-form-item label="答案解析：" prop="answer">
            <quill-editor
              @blur="$refs.questionsForm.validateField('answer')"
              v-model="questionsForm.answer"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="题目备注：" prop="remarks">
            <el-input
              style="width: 400px"
              type="textarea"
              v-model="questionsForm.remarks"
            ></el-input>
          </el-form-item>
          <el-form-item label="试题标签：" prop="tags">
            <el-select
              style="width: 400px"
              v-model="questionsForm.tags"
              multiple
              placeholder="请选择试题标签"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitquestionsForm"
              >确认提交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { add, detail, update } from '../../api/hmmm/questions'
import { citys, provinces } from '../../api/hmmm/citys'
import { simple as getSubjectsList } from '@/api/hmmm/subjects'
import { simple as getDirectorysList } from '@/api/hmmm/directorys'
import { simple as gettagsList } from '@/api/hmmm/tags'
import { list as getCompanysList } from '@/api/hmmm/companys'

export default {
  name: 'Questions-New',
  data () {
    return {
      questionsForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 省份
        city: '', // 城市
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ], // 选项
        videoURL: '', // 解析地址
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      questionsRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ], // 学科
        catalogID: [
          { required: true, message: '请选择目录', trigger: ['blur', 'change'] }
        ], // 目录
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['blur', 'change'] }
        ], // 企业
        city: [
          {
            required: true,
            message: '请选择地区',
            trigger: 'change'
          }
        ], // 城市
        direction: [
          { required: true, message: '请选择方向', trigger: ['blur', 'change'] }
        ], // 方向
        questionType: [
          { required: true, message: '请选择题型', trigger: ['blur', 'change'] }
        ], // 题型
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ], // 难度
        question: [
          { required: true, message: '请输入题干', trigger: ['blur', 'change'] }
        ], // 题干
        videoURL: [
          {
            required: true,
            message: '请填写解析视频地址',
            trigger: ['blur', 'change']
          }
        ], // 解析地址
        answer: [
          {
            required: true,
            message: '请输入答案解析',
            trigger: ['blur', 'change']
          }
        ], // 答案解析
        remarks: [
          { required: true, message: '请填写备注', trigger: ['blur', 'change'] }
        ], // 题目备注
        tags: [
          { required: true, message: '请选中标签', trigger: ['blur', 'change'] }
        ] // 试题标签
      },

      subjectList: [], // 科目下拉列表
      directorysList: [], // 目录下拉列表
      companysList: [], // 企业下拉列表
      tagsList: [], // 进行标签下拉列表

      enLetter: '', // 单选多选项的字母
      letter: [], // 26个字母
      radioData: '', // 单选状态

      provinceList: [], // 省份列表
      cityList: [] // 城市列表
    }
  },
  async created () {
    // 获取学科简单列表
    this.getSubList()
    this.getComList()

    // 输出A-Z 26个大写字母
    this.getLetter()

    // 获取城市
    this.provinceList = provinces()

    // 获取详情修改数据
    this.getQuestionsDetail()
  },
  watch: {
    radioData: {
      handler (newCode) {
        this.questionsForm.options.forEach((item) => {
          if (item.code === newCode) {
            item.isRight = true
          } else {
            item.isRight = false
          }
        })
      }
    },
    $route () {
      this.questionsForm.options = [
        { code: 'A', title: '', img: '', isRight: false },
        { code: 'B', title: '', img: '', isRight: false },
        { code: 'C', title: '', img: '', isRight: false },
        { code: 'D', title: '', img: '', isRight: false }
      ] // 选项
      this.radioData = ''
      this.tagsList = []
      this.questionsForm = {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 省份
        city: '', // 城市
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ], // 选项
        videoURL: '', // 解析地址
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      }
      this.$nextTick(() => {
        this.$refs.questionsForm.clearValidate()
      })
    }
  },
  methods: {
    // 获取学科简单列表
    async getSubList () {
      const { data: subjectList } = await getSubjectsList()
      this.subjectList = subjectList
    },
    // 获取企业简单列表
    async getComList () {
      const {
        data: { items }
      } = await getCompanysList() // : companysList
      this.companysList = items
    },
    // 获取26个字母
    getLetter () {
      const arr = []
      for (let i = 0; i < 26; i++) {
        arr.push(String.fromCharCode(65 + i))
      }
      this.letter = arr
    },

    // 表单提交
    async submitquestionsForm () {
      this.$refs.questionsForm.validate(async (valid) => {
        if (!valid) return
        if (this.$route.query.id) {
          const isTags = this.questionsForm.tags instanceof Array
          if (isTags) {
            this.questionsForm.tags = this.questionsForm.tags.join(',')
          }
          await update(this.questionsForm)
          this.$message.success('修改试题成功')
        } else {
          this.questionsForm.tags = this.questionsForm.tags.join(',')
          await add(this.questionsForm)
          this.$message.success('试题录入成功')
        }
        this.$router.back()
      })
    },

    // 上传图片功能
    changeUpload (code) {
      this.enLetter = code
    },
    handleAvatarSuccess (res, file) {
      const index = this.questionsForm.options.findIndex(
        (item) => item.code === this.enLetter
      )
      this.questionsForm.options[index].img =
        'http://192.168.69.128:3030/' + res.url
    },
    // 关闭上传
    closeUploadImg (index) {
      this.questionsForm.options[index].img = ''
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 添加选项
    addOptions () {
      const opts = this.questionsForm.options
      opts.push({
        code: this.letter[opts.length],
        title: '',
        img: '',
        isRight: false
      })
    },

    // 获取城市
    changeCity () {
      this.cityList = citys(this.questionsForm.province)
    },
    // 切换选择类型显示单选多选
    changeType () {
      if (this.questionsForm.questionType === '1') {
        this.questionsForm.options = [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ]
      }
    },
    // 下拉菜单学科
    async changeSubject (id) {
      // 获取目录列表
      const { data: directorysList } = await getDirectorysList({
        subjectID: id
      })
      this.directorysList = directorysList
      // 获取试题标签列表
      const { data: tagsList } = await gettagsList({
        subjectID: id
      })
      this.tagsList = tagsList
      this.questionsForm.catalogID = ''
      this.questionsForm.tags = []
    },
    // 获取详情修改数据
    async getQuestionsDetail () {
      // 获取路由参数
      if (this.$route.query.id) {
        const { data } = await detail({ id: this.$route.query.id })
        // 1. 解决返回数据的单选多选的选中状态
        data.options.forEach((item) => {
          if (item.isRight === 1) {
            this.radioData = item.code
            item.isRight = true
          } else {
            item.isRight = false
          }
        })
        // 2. 解决数据返回的字母是随机的
        const arr = []
        this.letter.forEach((item) => {
          data.options.forEach((value) => {
            if (item === value.code) {
              arr.push(value)
            }
          })
        })
        data.options = arr

        // 3. 获取目录列表
        const { data: directorysList } = await getDirectorysList({
          subjectID: data.subjectID
        })
        this.directorysList = directorysList
        // 4. 获取试题标签列表
        const { data: tagsList } = await gettagsList({
          subjectID: data.subjectID
        })
        this.tagsList = tagsList

        // 5. 把修改返回回来的试题标签的字符串转换为数组
        data.tags = data.tags.split(',')

        // 6. 解决数据类型问题进行数据回显
        this.questionsForm = data

        setTimeout(() => {
          this.$nextTick(() => {
            document.documentElement.scrollTop = 0
          })
        }, 0)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 20px;
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }
  ::v-deep .quill-editor .ql-container {
    height: 200px;
  }
  .radio-options {
    margin: 20px 0;
    ::v-deep .radio-input {
      width: 240px;
      margin-right: 5px;
    }
    .father-a {
      position: relative;
      display: inline-block;
      .uploader-img {
        display: inline-block;
        width: 100px;
        height: 60px;
        line-height: 60px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        overflow: hidden;
        vertical-align: middle;
        text-align: center;
      }
    }

    ::v-deep .upload-close {
      position: absolute;
      right: -9px;
      top: -6px;
      width: 15px;
      height: 15px;
      line-height: 12px;
      text-align: center;
      color: #999;
      border: 1px solid #999;
      border-radius: 50%;
    }

    ::v-deep .uploader-img:hover {
      border-color: #409eff;
    }
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: '';
  }
  .clearfix:after {
    clear: both;
  }
}
</style>
